/**
 * Created by hldev on 17-2-6.
 */
import {Iterable} from "immutable";
import thunkMiddleware from "redux-thunk";
import {combineReducers, createStore, applyMiddleware} from "redux";

const stateNameList = [
    'user',
    'sign',
    'records',
    'article',
    'file',
];
const state = {};
for (name of stateNameList) {
    state[name] = require(`./${name}/${name}Reducer`);
}

const middlewares = [thunkMiddleware];

if (process.env.NODE_ENV === 'development') {
    const createLogger = require('redux-logger');
    const logger = createLogger({
        stateTransformer: (state) => {
            let newState = {};
            for (let i of Object.keys(state)) {
                if (Iterable.isIterable(state[i])) {
                    newState[i] = state[i].toJS();
                } else {
                    newState[i] = state[i];
                }
            }
            return newState;
        }
    });
    middlewares.push(logger);
}

const reducers = combineReducers(state);

export function configureStore(initialState = {}) {
    const store = createStore(
        reducers,
        initialState,
        applyMiddleware(...middlewares)
    );

    if (module.hot) {
        console.log('module.hot', module.hot);
        // Enable Webpack hot module replacement for reducers
        module.hot.accept('./reducers', () => {
            const nextRootReducer = reducers;
            store.replaceReducer(nextRootReducer);
        });
    }

    return store;
}

const store = configureStore();

export default store;